package tasks;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import constant.CommonConstant;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

/**
 * @describe: 实现本地数据上传至 AIStaion
 * @author: 容若
 * @created: 2024-08-07 11:04
 */
public class LoadFile {
    public String loadFile(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        String fileName = file.getName();
        int dotIndex = fileName.lastIndexOf('.');
        String extension = "";
        if (dotIndex != -1) {
            extension = fileName.substring(dotIndex);
        }
        return generatePstRequest(extension, file);
    }

    private String generatePstRequest(String extension, File file) throws IOException {
        // 请求头的 Map
        HashMap<String, String> headers = new HashMap<>();
        headers.put(CommonConstant.CONTENT_TYPE, CommonConstant.TYPE);
        headers.put(CommonConstant.AUTH_TOKEN, CommonConstant.TOKEN);
        StrBuilder response = new StrBuilder();
        // 读取文件
        byte[] fileContent = Files.readAllBytes(file.toPath());
        int partCount = (int) Math.ceil((double) fileContent.length / CommonConstant.PART_SIZE);
        for (int i = 0; i < partCount; i++) {
            StrBuilder strBuilder = new StrBuilder();
            strBuilder.append(i + 1).append(extension);
            // 计算每一片的起始位置和结束位置
            int start = i * CommonConstant.PART_SIZE;
            int end = Math.min(start + CommonConstant.PART_SIZE, fileContent.length);
            // 获取每一片的内容
            int currPart = i + 1;
            byte[] partContent = copyOfRange(fileContent, start, end);
            System.out.println("开始上传第" + currPart + "个分片的数据.....");
            HttpRequest request = HttpUtil.createPost(CommonConstant.AI_URI)
                    .headerMap(headers, true)
                    .form("file", partContent, strBuilder.toString())
                    .form("uuid", UUID.fastUUID().toString())
                    .form("chunk", currPart)
                    .form("totalChunk", partCount)
                    .form("path", CommonConstant.LOAD_PATH + "/" + getDate())
                    .form("fileModel", 2)
                    .form("fileName", strBuilder.toString())
                    .form("chunkSize", 4194304)
                    .form("fileSize", partContent.length)
                    .form("storageName", "master");
            response.append(request.execute().body());
            System.out.println("第" + currPart + "个分片数据上传成功!");
        }
        return response.toString();
    }

    // 从原数组中复制一部分
    public byte[] copyOfRange(byte[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException("from(" + from + ") > to(" + to + ")");
        byte[] copy = new byte[newLength];
        System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
        return copy;
    }

    private String getDate() {
        // 获取当前日期
        LocalDate date = LocalDate.now();

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return date.format(formatter);
    }
}
